package cn.edu.fudan.tools;

import cn.edu.fudan.type.DataItem;

import java.util.List;

public class BinarySearch {
	public int binarySearch(List<DataItem> data, long timepoint, int flag){
		int begin = 0;
		int end = data.size()-1;
		int mid = 0;
		while(begin <= end){
			mid = (begin+end)/2;
			if(timepoint < data.get(mid).getTimestamp()){
				end = mid;
			}else if(timepoint > data.get(mid).getTimestamp()){
				begin = mid;
			}else{
				return mid;
			}
			if(end - begin == 1){
				if(timepoint < data.get(begin).getTimestamp()) return begin;
				if(timepoint >= data.get(end).getTimestamp()) return end;
				if(timepoint > data.get(begin).getTimestamp() && timepoint < data.get(end).getTimestamp()) {
					if(flag == 1)
						return begin;
					else return end;
				}
			}
		}
		return -(begin+1);
	}
}
